package com.leetcode.math;

public class GenerateMatrix {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        boolean[][] isUsed = new boolean[n][n];
        int total = n * n;
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int directIndex = 0;
        int row = 0;
        int col = 0;
        for (int i = 1; i <= total; i++) {
            matrix[row][col] = i;
            isUsed[row][col] = true;
            int nextRow = row + directions[directIndex][0];
            int nextCol = col + directions[directIndex][1];
            if (nextRow < 0 || nextRow >= n || nextCol < 0 || nextCol >= n
            || isUsed[nextRow][nextCol]) {
                directIndex = (directIndex  + 1) % 4;
            }
            row += directions[directIndex][0];
            col += directions[directIndex][1];
        }
        return matrix;
    }
}
